package com.ikas.ai.utils;

import com.github.pagehelper.page.PageMethod;
import org.apache.commons.lang3.StringUtils;

/**
 * @program: 分页工具类
 * @description:
 * @author: HXH
 * @create: 2021-10-27 19:35
 **/
public class PageUtil {

    private PageUtil() {

    }

    public static void configPageHelper(Integer pageNum, Integer pageSize, String columnName, String sortOrder, String defaultColumnName, String defaultSortOrder) {
        if (pageNum != null && pageSize != null) {
            PageMethod.startPage(pageNum, pageSize);
            if (StringUtils.isNotBlank(columnName) && StringUtils.isNotBlank(sortOrder)) {
                if (StringUtils.isBlank(defaultColumnName) || StringUtils.isBlank(defaultSortOrder) || columnName.equals(defaultColumnName)) {
                    PageMethod.orderBy(humpToUnderline(columnName) + " " + sortOrder);
                } else {
                    PageMethod.orderBy(humpToUnderline(columnName) + " " + sortOrder + "," + humpToUnderline(defaultColumnName) + " " + defaultSortOrder);
                }
            } else {
                PageMethod.orderBy(humpToUnderline(defaultColumnName) + " " + defaultSortOrder);
            }
        }
    }

    public static void configPageHelper(Integer pageNum, Integer pageSize, String columnName, String sortOrder, boolean count) {
        if (pageNum != null && pageSize != null) {
            PageMethod.startPage(pageNum, pageSize, count);
            if (StringUtils.isNotBlank(columnName) && StringUtils.isNotBlank(sortOrder)) {
                PageMethod.orderBy(humpToUnderline(columnName) + " " + sortOrder);
            }
        }
    }

    private static String humpToUnderline(String source) {
        return source.replaceAll("[A-Z]", "_$0").toLowerCase();
    }
}
